import useToast from '@/hooks/useToast';

/**
 * 支付工具函数
 * @param paymentData
 * @returns Promise<void> - 支付结果，成功则 resolve，无需返回数据，失败则 reject 错误信息
 */
const { showToast } = useToast();
export const requestPayment = (paymentData: UniApp.RequestPaymentOptions): Promise<void> => {
  return new Promise((resolve, reject) => {
    if (!paymentData || !paymentData.timeStamp || !paymentData.nonceStr || !paymentData.package || !paymentData.signType || !paymentData.paySign) {
      showToast('支付参数不完整，请联系客服');
      reject(new Error('支付参数不完整'));
      return;
    }

    // 调用 uni.requestPayment
    uni.requestPayment({
      ...paymentData,
      success: () => {
        resolve();
      },
      fail: (error) => {
        // 处理用户主动取消支付的情况
        if (error.errMsg === 'requestPayment:fail cancel') {
          showToast('取消支付');
          reject(new Error('取消支付'));
        } else {
          showToast(error.errMsg || '支付失败');
          reject(new Error(error.errMsg || '支付失败'));
        }
      },
    });
  });
};
